import React, {useEffect} from 'react';
import {Button, Carousel, Col, Form, Input, Row, Spin} from 'antd';
import {LockOutlined, SafetyOutlined, UserOutlined} from '@ant-design/icons';
import {isLogin, setCurrentUser, setToken} from '@/utils/authority';
import './index.less';
import querystring from 'query-string';
import {useLocation} from "react-router-dom";
import {getAppInfo, getMySelf, getVerifyCode, login} from "@/services/usercenter";
import {useRequest} from "ahooks";
import {useForm} from "antd/es/form/Form";
import useProjectConfig from "@/hooks/useProjectConfig.ts";
import Cyjc3TempImg from "@/components/Cyjc3TempImg";

const Login: React.FC<{ name: string }> = ({name}) => {
    const projectConfig = useProjectConfig();
    const [form] = useForm();
    const {search} = useLocation();
    const {token, redirect}: any = querystring.parse(search);

    useEffect(() => {
        document.title = name;
    }, [])

    //跳转到首页
    const navigateToHomePage = () => {
        if (!redirect) {
            // if (projectConfig?.recordVO?.pcHomePageUrl) {
            //     window.location.href = projectConfig?.recordVO?.pcHomePageUrl;
            // } else {
                // getAppInfo().then((res: any) => {
                    // window.location.href = res?.recordVO?.pcHomePageUrl || "/";
                    window.location.href="/"
            //     })
            // }
        } else {
            // window.location.href = redirect;
        }
    }

    //如果localStorage存在token和用户，跳到首页
    if (isLogin()) {
        navigateToHomePage();
    }

    //获取token成功后调用此方法
    const loginSuccess = (accessToken: any) => {
        setToken(accessToken);
        getMySelf().then((user: any) => {
            if (user) {
                setCurrentUser(user);
                navigateToHomePage();
            }
        });
    }

    //如果url上携带了token
    if (token) {
        loginSuccess(token)
    }


    const {
        data: verifyToken,
        run: runGetVerifyCode
    } = useRequest(getVerifyCode)

    const {loading, run: runLogin} = useRequest(login, {
        manual: true,
        onSuccess: (res: any) => {
            const {access_token = ''} = res;
            if (access_token) {
                loginSuccess(access_token)
            }
        },
        onError: () => {
            runGetVerifyCode();
        }
    })

    const onFinish = () => {
        form.validateFields().then((fields: any) => {
            runLogin({...fields, verify_token: verifyToken});
        });
    };

    return (
        <div id="login-page">
            <div className="login-title">{projectConfig?.name}</div>
            <Form
                form={form}
                name="normal_login"
                id="login-form"
                size="large"
                initialValues={{
                    auth_type: 'vc'
                }}
                onFinish={onFinish}
            >
                <div className="form-title">欢迎登录</div>
                <Form.Item name="auth_type" hidden>
                    <Input/>
                </Form.Item>
                <Form.Item name="verify_token" hidden>
                    <Input/>
                </Form.Item>
                <Form.Item
                    name="username"
                    rules={[{required: true, message: '请输入用户名！'}]}
                >
                    <Input
                        prefix={<UserOutlined className="site-form-item-icon"/>}
                        placeholder="用户名"
                    />
                </Form.Item>
                <Form.Item
                    name="password"
                    rules={[{required: true, message: '请输入密码！'}]}
                >
                    <Input
                        prefix={<LockOutlined className="site-form-item-icon"/>}
                        type="password"
                        placeholder="用户密码"
                    />
                </Form.Item>
                <Form.Item>
                    <Row gutter={8}>
                        <Col span={12}>
                            <Form.Item
                                name="verify_code"
                                noStyle
                                rules={[{required: true, message: '请输入验证码！'}]}
                            >
                                <Input
                                    prefix={<SafetyOutlined className="site-form-item-icon"/>}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12} className="verify-code-img-wrap">
                            <Spin spinning={!verifyToken}>
                                {verifyToken && (
                                    <img
                                        className="verify-code-img"
                                        src={`${__API_BASE_URL__}/usercenter/login/getVerifyImage?verifyToken=${verifyToken}`}
                                        onClick={runGetVerifyCode}
                                        alt={'验证码读取失败'}/>
                                )}
                            </Spin>
                        </Col>
                    </Row>
                </Form.Item>

                <Form.Item>
                    <Button
                        loading={loading}
                        htmlType="submit"
                        type="primary"
                        className="login-form-button"
                    >
                        登录
                    </Button>
                </Form.Item>
            </Form>
            {projectConfig?.configVO?.picUrl?.endsWith('mp4') ? (
                <video className="bg-video" loop={true} autoPlay muted>
                    <source src={projectConfig?.configVO?.picUrl} type="video/mp4"/>
                </video>
            ) : (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    zIndex: -1,
                }}
                >
                    <Carousel autoplay={true} effect="fade">
                        {projectConfig && projectConfig.configVO?.picUrl
                            ? projectConfig.configVO.picUrl.split('####').map(
                                (item: any, index: number) => {
                                    return <Cyjc3TempImg key={index} src={item} className={'w-screen h-screen'}/>
                                })
                            : ''}
                    </Carousel>
                </div>
            )}
        </div>
    );
}

export default Login;
